package com.apes.fico.masterdata.gl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.fico.masterdata.gl.model.AccountingVoucherType;
import com.apes.fico.masterdata.gl.respository.AccountingVoucherTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName AccountingVoucherTypeService
 * @Description TODO
 * @Author pengyb
 * @Date 2018/12/27 14:58
 * @Version 1.0
 **/
@Service("accountingVoucherTypeService")
public class AccountingVoucherTypeService extends DomainService {
    @Autowired
    private AccountingVoucherTypeRepository accountingVoucherTypeRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public AccountingVoucherType save(SimpleRequest request) {
        AccountingVoucherType accountingVoucherType = request.getO(AccountingVoucherType.class);
        accountingVoucherType.setCreateDate(new Date());
        return accountingVoucherTypeRepository.saveAndFlush(accountingVoucherType);
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    public AccountingVoucherType update(SimpleRequest request) {
        checkData(request);
        AccountingVoucherType accountingVoucherType = request.getO(AccountingVoucherType.class);
        accountingVoucherType.setUpdateDate(new Date());
        return accountingVoucherTypeRepository.saveAndFlush(accountingVoucherType);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        checkData(request);
        AccountingVoucherType accountingVoucherType = request.getO(AccountingVoucherType.class);
        accountingVoucherTypeRepository.delete(accountingVoucherType.getId());
        return "删除成功";
    }

    /**
     * 检查
     *
     * @param request
     */
    public void checkData(SimpleRequest request) {
        AccountingVoucherType accountingVoucherType = accountingVoucherTypeRepository.findOne((String) request.get("id"));
        if (accountingVoucherType == null) throw new RuntimeException("凭证" + accountingVoucherType.getId() + "不存在");
        if (accountingVoucherType.getVersion() != (int) request.get("version"))
            throw new RuntimeException("凭证" + accountingVoucherType.getId() + "已更新或已删除");
    }

    /**
     * 取凭证的第一行数据
     * @return
     */
    public AccountingVoucherType findFirstLine(){
        AccountingVoucherType accountingVoucherType=accountingVoucherTypeRepository.findAll().get(0);
        return accountingVoucherType;
    }
}
